//
//  ViewController.m
//  PhotoKit
//
//  Created by Guo Rui on 2017/10/12.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "ViewController.h"
#import <Photos/Photos.h>
#import <SDWebImageDownloader.h>
#import "PHAssetCollection+Ex.h"
#import "PHPhotoLibrary+Ex.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
    
        // 用户没有选择过. 向用户询问权限
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        // 这个block是异步调用的。
        dispatch_async(dispatch_get_main_queue(), ^{
            // 1. 用户授权
            if (status == PHAuthorizationStatusAuthorized) {
                // 可以进行相册操作
                [self save];
            }
            // 2. 用户拒绝过访问相册
            else if (status == PHAuthorizationStatusDenied && oldStatus != PHAuthorizationStatusNotDetermined) {
                // oldStatus != PHAuthorizationStatusNotDetermined 这个判断的目的是防止用户在选择不允许访问的时候，进入这里弹框引导用户去打开。
                NSLog(@"提示用户去设置中打开权限");
            }
            // 3. 功能被限制。例如：家长控制.
            else if (status == PHAuthorizationStatusRestricted) {
                NSLog(@"因系统原因，无法访问相册");
            }
        });
    }];
    
}

- (void)save
{
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:@"https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=258115418,3220231084&fm=173&s=292AED139FAB440B1250F1C90000D0B3&w=600&h=296&img.JPEG"] options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        // 创建PHAsset并保存
        NSError *e = nil;
        [PHAssetCollection saveImage:image toCollectionWithTitle:@"ccc" error:&e];
        if (e) {
            NSLog(@"保存失败");
        }
        else {
            NSLog(@"保存成功");
        }
    }];
}

- (void)saveImage:(UIImage *)image toAlbumWithName:(NSString *)name error:(NSError *__autoreleasing *)error
{
    // 获取资源对象
    PHAsset *asset = [PHAssetCollection saveCamerRollWithImage:image error:error];
    if (*error) {
        return;
    }
    
    // 获取相册
    PHAssetCollection *collection = [PHPhotoLibrary createPHAssetCollectionWithTitle:name error:error];
    if (*error) {
        return;
    }
    
    // 将图片保存到这个相册的第一个位置上
    [collection saveAsset:asset error:error];
}

- (void)createPHAssetCollectionWithTitle:(NSString *)title completion:(void (^)(PHAssetCollection *))completion
{

    /**
     typedef NS_ENUM(NSInteger, PHAssetCollectionType) {
     PHAssetCollectionTypeAlbum      = 1, // 用户相册
     PHAssetCollectionTypeSmartAlbum = 2, // 系统相册（camerRoll）
     PHAssetCollectionTypeMoment     = 3, // 时刻相册，按时间排序
     } PHOTOS_ENUM_AVAILABLE_IOS_TVOS(8_0, 10_0);
     */
    
//    [PHPhotoLibrary createPHAssetCollectionWithTitle:title completion:^(PHAssetCollection *collection, NSError *error) {
//        if (completion) {
//            completion(collection);
//        }
//    }];
    
    NSError *error = nil;
    PHAssetCollection *collection = [PHPhotoLibrary createPHAssetCollectionWithTitle:title error:&error];
    if (completion) {
        completion(collection);
    }
}

/**
 保存图片进系统相册
 */
- (void)saveImageToCamerRoll
{
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:@"https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=2282459383,3985494631&fm=173&s=457839C44A1F34D40355E58E0300C080&w=600&h=450&img.JPEG"] options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        // 创建PHAsset并保存
//        [PHAssetCollection saveCamerRollWithImage:image completion:^(PHAsset *asset, NSError *error) {
//            NSLog(@"%@", asset);
//        }];
    }];
}

@end
